/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GrupoDialog.java
 *
 * Created on 20/10/2011, 23:14:56
 */
package br.com.seguradora.view.dialog;

import br.com.seguradora.exception.InputValidationException;
import br.com.seguradora.exception.PersistenciaException;
import br.com.seguradora.model.Plano;
import br.com.seguradora.model.Veiculo;
import br.com.seguradora.model.constant.StatusPlano;
import br.com.seguradora.service.PlanoService;
import br.com.seguradora.view.ErrorsList;
import br.com.seguradora.view.UserError;
import br.com.seguradora.view.StateEntityWindow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class PlanoDialog extends javax.swing.JDialog {

    private Plano plano;
    private Veiculo veiculo;
    private final static String titleWindow = "Plano";
    private StateEntityWindow stateEntity;

    public PlanoDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Plano plano) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        organizeWindow();
        setPlano(plano);
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        statusCombo = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        codigoLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        codigoVeiculoField = new javax.swing.JTextField();
        veiculoField = new javax.swing.JTextField();
        abrirVeiculosButton = new javax.swing.JButton();
        veiculoErrorLabel = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        codigoAssociadoField = new javax.swing.JTextField();
        associadoField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        dataEntradaField = new org.jdesktop.swingx.JXDatePicker();
        dataVencimentoField = new org.jdesktop.swingx.JXDatePicker();
        jLabel2 = new javax.swing.JLabel();
        dataEntradaErrorLabel = new javax.swing.JLabel();
        dataVencimentoErrorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        jLabel3.setText("Status:");

        statusCombo.setModel(new DefaultComboBoxModel(StatusPlano.values()));

        jLabel4.setText("Código:");

        codigoLabel.setText("0");

        jLabel5.setText("Veículo:");

        codigoVeiculoField.setEditable(false);
        codigoVeiculoField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        codigoVeiculoField.setFocusable(false);

        veiculoField.setEditable(false);
        veiculoField.setFocusable(false);

        abrirVeiculosButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/magnifier.png"))); // NOI18N
        abrirVeiculosButton.setToolTipText("Abrir pesquisa de veículos");
        abrirVeiculosButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        abrirVeiculosButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abrirVeiculosButtonActionPerformed(evt);
            }
        });

        veiculoErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        jLabel6.setText("Associado:");

        codigoAssociadoField.setEditable(false);
        codigoAssociadoField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        codigoAssociadoField.setFocusable(false);

        associadoField.setEditable(false);
        associadoField.setFocusable(false);

        jLabel1.setText("Data entrada:");

        dataEntradaField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dataEntradaFieldActionPerformed(evt);
            }
        });

        jLabel2.setText("Data vencimento:");

        dataEntradaErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        dataVencimentoErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dataVencimentoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dataVencimentoErrorLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(codigoVeiculoField, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(veiculoField, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(abrirVeiculosButton, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(veiculoErrorLabel))
                    .addComponent(statusCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(codigoLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(codigoAssociadoField, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(associadoField, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dataEntradaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dataEntradaErrorLabel)))
                .addContainerGap(22, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 613, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(122, 122, 122)
                .addComponent(confirmarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addContainerGap(291, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(codigoLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(statusCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(veiculoErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(abrirVeiculosButton, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel5)
                                .addComponent(codigoVeiculoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(veiculoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel6)
                                .addComponent(codigoAssociadoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(associadoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(dataEntradaErrorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(dataEntradaField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(dataVencimentoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2))
                                .addComponent(dataVencimentoErrorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE))
                            .addGap(18, 18, 18))))
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton)
                    .addComponent(cancelarButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            PlanoService planoService = new PlanoService();
            Plano plano = getPlano();
            if (getStateEntity() == StateEntityWindow.NEW) {
                if (planoService.hasPlano(plano.getVeiculo())) {
                    JOptionPane.showMessageDialog(this, "O veículo informado já possui um plano em vigor,\n"
                            + "sendo necessário finalizar ou cancelar o atual para realizar um novo plano.", "Mensagem do sistema", 1);
                    return;
                } else {
                    planoService.inserir(plano);
                }
            } else if (getStateEntity() == StateEntityWindow.UPDATE) {
                planoService.atualizar(plano);
            }
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
    }//GEN-LAST:event_confirmarButtonActionPerformed

    private void abrirVeiculosButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_abrirVeiculosButtonActionPerformed
        ConsultaVeiculoDialog dialog = new ConsultaVeiculoDialog(new javax.swing.JFrame(), true, StateEntityWindow.SEARCH);
        dialog.setSelectEntity(true);
        dialog.setVisible(true);
        Veiculo veiculo = dialog.getVeiculo();
        setVeiculo(veiculo);
}//GEN-LAST:event_abrirVeiculosButtonActionPerformed

    private void dataEntradaFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataEntradaFieldActionPerformed
        Date dataEntrada = dataEntradaField.getDate();
        Calendar cal = Calendar.getInstance();
        cal.setTime(dataEntrada);
        cal.add(Calendar.MONTH, 12);
        Date dataVencimento = cal.getTime();
        dataVencimentoField.setDate(dataVencimento);
    }//GEN-LAST:event_dataEntradaFieldActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                PlanoDialog dialog = new PlanoDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton abrirVeiculosButton;
    private javax.swing.JTextField associadoField;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JTextField codigoAssociadoField;
    private javax.swing.JLabel codigoLabel;
    private javax.swing.JTextField codigoVeiculoField;
    private javax.swing.JButton confirmarButton;
    private javax.swing.JLabel dataEntradaErrorLabel;
    private org.jdesktop.swingx.JXDatePicker dataEntradaField;
    private javax.swing.JLabel dataVencimentoErrorLabel;
    private org.jdesktop.swingx.JXDatePicker dataVencimentoField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JComboBox statusCombo;
    private javax.swing.JLabel veiculoErrorLabel;
    private javax.swing.JTextField veiculoField;
    // End of variables declaration//GEN-END:variables

    private void setPlano(Plano plano) {
        if (plano == null) {
            return;
        }
        this.plano = plano;
        codigoLabel.setText(String.valueOf(plano.getId()));
        statusCombo.setSelectedItem(plano.getStatus());
        setVeiculo(plano.getVeiculo());
        dataEntradaField.setDate(plano.getDataEntrada());
        dataVencimentoField.setDate(plano.getDataVencimento());
    }

    private Plano getPlano() {
        if (plano == null) {
            plano = new Plano();
        }
        plano.setStatus((StatusPlano) statusCombo.getSelectedItem());
        plano.setVeiculo(getVeiculo());
        plano.setDataEntrada(dataEntradaField.getDate());
        plano.setDataVencimento(dataVencimentoField.getDate());
        return plano;
    }

    private void organizeWindow() {
        if (getStateEntity() == StateEntityWindow.NEW) {
            statusCombo.setEnabled(false);
        } else {
            abrirVeiculosButton.setEnabled(false);
        }
        isShowErrorsLabel(false);
    }

    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }

    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if (codigoVeiculoField.getText().isEmpty()) {
            errorsList.addError(new UserError(veiculoErrorLabel, "O veículo não foi informado."));
        }
        if (dataEntradaField.getDate() == null) {
            errorsList.addError(new UserError(dataEntradaErrorLabel, "A data de entrada não foi informada."));
        }
        if (dataVencimentoField.getDate() == null) {
            errorsList.addError(new UserError(dataVencimentoErrorLabel, "A data de vencimento não foi informada."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }

    private void isShowErrorsLabel(boolean show) {
        veiculoErrorLabel.setVisible(show);
        dataEntradaErrorLabel.setVisible(show);
        dataVencimentoErrorLabel.setVisible(show);
    }

    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }

    public Plano objetoPlano() {
        return plano;
    }

    private void setVeiculo(Veiculo veiculo) {
        if (veiculo != null) {
            this.veiculo = veiculo;
            codigoVeiculoField.setText(String.valueOf(veiculo.getId()));
            veiculoField.setText(veiculo.toString());
            codigoAssociadoField.setText(String.valueOf(veiculo.getAssociado().getId()));
            associadoField.setText(veiculo.getAssociado().getNome());
        }
    }

    public Veiculo getVeiculo() {
        return veiculo;
    }
    
    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
